#include <48func.h>
int main(int argc, char *argv[])
{
    // ./5_aqiang 1.pipe 2.pipe
    ARGS_CHECK(argc,3);
    int fdw = open(argv[1],O_WRONLY);
    ERROR_CHECK(fdw,-1,"open fdw");
    int fdr = open(argv[2],O_RDONLY);
    ERROR_CHECK(fdr,-1,"open fdr");
    printf("chat established!\n");
    char buf[4096] = {0};
    fd_set rdset;//创建监听集合
    while(1){
        FD_ZERO(&rdset);//初始化监听集合
        FD_SET(STDIN_FILENO,&rdset);//监听stdin
        FD_SET(fdr,&rdset);//监听2.pipe管道的读端
        struct timeval tv;
        tv.tv_sec = 3;
        tv.tv_usec = 0;
        int ret = select(fdr+1,&rdset,NULL,NULL,&tv);
        if(ret == 0){
            printf("timeout\n");
            continue;
        }
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            // 说明stdin有数据
            memset(buf,0,sizeof(buf));
            read(STDIN_FILENO,buf,sizeof(buf));
            write(fdw,buf,strlen(buf));
        }
        if(FD_ISSET(fdr,&rdset)){
            // 说明管道有数据
            memset(buf,0,sizeof(buf));
            ssize_t sret = read(fdr,buf,sizeof(buf));
            //当sret为0时，说明对方已经关闭了
            if(sret == 0){
                printf("hehe!\n");
                break;
            }
            printf("buf = %s\n", buf);
        }
    }
    close(fdr);
    close(fdw);
    return 0;
}

